# 导入Django框架需要的模块
from django.core.management.base import BaseCommand
# 导入MySQL驱动
import pymysql
from django.conf import settings

# 设置Django的环境变量
# os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'promotion.settings')
# django.setup()

# 导入settings.py中的DATABASES配置
DATABASES = settings.DATABASES
# 获取默认数据库配置
db_config = DATABASES['default']


class MySql:
    def __init__(self, config) -> None:
        self.config = config

    def try_create_database(self):
        db_name = self.config['NAME']

        with pymysql.connect(
            host=self.config['HOST'],
            port=int(self.config['PORT']),
            user=self.config['USER'],
            password=self.config['PASSWORD'],
            charset='utf8mb4',
        ) as conn:
            # 创建游标对象
            with conn.cursor() as cursor:
                # 执行SQL语句，创建表格等操作
                try:
                    sql = f'CREATE DATABASE {db_name}'
                    cursor.execute(sql)
                except Exception as e:
                    if not 'database exists' in str(e):
                      print(f'Error executing sql ({str(e)}): {sql}')


class Command(BaseCommand):
    help = 'Create database'

    def handle(self, *args, **options):
      # 调用初始化MySQL数据库的函数
      # 不是mysql就不用创建database
      if 'mysql' in db_config['ENGINE']:
          MySql(db_config).try_create_database()
